import { BASE_URL, USER_API, APPID, REDIRECT_URI } from "@/settings";
import request from "@/utils/request";
import { getUrlKey } from "@/utils/tools";

// 更换手机号获取验证码
export function sendCodeReq(data) {
  return request({
    url: `${BASE_URL}${USER_API}/certifications/commonSendCodeByScene`,
    method: "post",
    data
  });
}
// 获取凭证
export function checkCodeReq(data) {
  return request({
    url: `${BASE_URL}${USER_API}/certifications/checkCodeByTokenTrue`,
    method: "post",
    data
  });
}
// 第二步获取验证码
export function commonSendCodeReq(data) {
  return request({
    url: `${BASE_URL}${USER_API}/certifications/commonSendCode`,
    method: "post",
    data
  });
}
// 修改手机号1
export function updatePhoneReq(data) {
  return request({
    url: `${BASE_URL}/hr/api/v1/empInfos/updatePhone`,
    method: "post",
    data: data
  });
}

export function tokenCheckReq(token) {
  return request({
    url: `${BASE_URL}${USER_API}/token/check`,
    method: "post",
    data: JSON.stringify(token)
  });
}

export function loadEmpInfoReq() {
  return request({
    url: `${BASE_URL}/hr/api/v1/login/getEmpAllInfoByToken2`,
    method: "get"
  });
}

export function loadPermissionReq() {
  return request({
    url: `${BASE_URL}/hr/api/v1/permissions/listUserPermissionForApp`,
    method: "get"
  });
}

export function switchSiteReq(siteId) {
  return request({
    url: `${BASE_URL}/user/api/v1/token/switch2`,
    method: "post",
    data: JSON.stringify(siteId)
  });
}
export function switchSiteReqOld(siteId) {
  return request({
    url: `${BASE_URL}/user/api/v1/token/switch`,
    method: "post",
    data: JSON.stringify(siteId)
  });
}
function handleLoginInfo(res) {
  if (res.nickName) {
    uni.setStorageSync("name", res.nickName);
  }
  if (res.headImgUrl) {
    uni.setStorageSync("avatar", res.headImgUrl);
  }
  if (res.userLoginVO && res.userLoginVO.verified) {
    uni.setStorageSync("token", res.userLoginVO.jwtTokenDTO.token);
    uni.setStorageSync("userId", res.userLoginVO.userVO.id);
    uni.setStorageSync("name", res.userLoginVO.userVO.name);
    uni.setStorageSync("phone", res.userLoginVO.userVO.phone);
    uni.setStorageSync("siteId", res.userLoginVO.userVO.siteId);
    uni.setStorageSync("avatar", res.userLoginVO.userVO.avatar);
    if (res.empAllInfoVO) {
      uni.setStorageSync(
        "empId",
        res.empAllInfoVO ? res.empAllInfoVO.id : null
      );
      uni.setStorageSync(
        "userStatus",
        res.empAllInfoVO ? res.empAllInfoVO.status : null
      );
      console.log("userStatus1", res);
      if (uni.getStorageSync("redirectUrl")) {
        uni.redirectTo({
          url: `/pages/index/index?redirect=${uni.getStorageSync(
            "redirectUrl"
          )}`
        });
      } else {
        uni.redirectTo({
          url: `/pages/index/index`
        });
      }
    } else {
      uni.showToast({
        title: "花名册中未检测到员工",
        icon: "none",
        duration: 1000
      });
      const loadingTimer = setTimeout(() => {
        uni.redirectTo({
          url: "/pages/index/index"
        });
        clearTimeout(loadingTimer);
      }, 1000);
    }
  } else {
    if (res.userLoginVO) {
      uni.setStorageSync("unionId", res.userLoginVO.unionId);
    }
    uni.redirectTo({
      url: "/authorize/login"
    });
  }
}

export function loginCheckH5() {
  // const ua = window.navigator.userAgent.toLowerCase()
  // if(ua.match(/MicroMessenger/i) === 'micromessenger'){
  const code = getUrlKey("code");
  const state = getUrlKey("state");
  if ((code, state)) {
    request({
      url: `${BASE_URL}/hr/api/v1/login/wechat/web`,
      method: "post",
      data: {
        code: code,
        state: state,
        terminalType: "B"
      }
    }).then(res => {
      handleLoginInfo(res);
    });
  } else {
    const state = Math.ceil(Math.random() * 1000);
    location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
  }
  // }else{
  //   uni.redirectTo({
  //     url: '/authorize/login'
  //   })
  // }
}

export function loginCheckMp() {
  uni.authorize({
    scope: "scope.userInfo",
    success: () => {
      if (uni.getStorageSync("token")) {
        weixinCheck();
      } else {
        uni.redirectTo({
          url: "/authorize/index"
        });
      }
    },
    fail: () => {
      uni.redirectTo({
        url: "/authorize/index"
      });
    }
  });
}

export function loginByWechat(data) {
  return request({
    url: `${BASE_URL}/hr/api/v1/login/wechat/xcx`,
    method: "post",
    data: {
      ...data,
      terminalType: "B"
    }
  });
}

export function weixinCheck(params) {
  // uni.login({
  //   provider: "weixin",
  //   success: loginRes => {
  //     params = params || {};
  //     console.log("loginRes", loginRes);
  //     debugger;
  loginByWechat(params)
    .then(res => {
      uni.hideLoading();
      handleLoginInfo(res);
    })
    .catch(err => {
      console.log("debug log --> ", err);
      uni.showToast({
        title: err,
        icon: "none",
        duration: 2000
      });
      const timer = setTimeout(() => {
        uni.redirectTo({
          url: "/authorize/index"
        });
        clearTimeout(timer);
      }, 2000);
    });
  //   },
  //   fail: loginErr => {
  //     uni.showToast({
  //       title: loginErr,
  //       icon: "none",
  //       duration: 2000
  //     });
  //     const timer = setTimeout(() => {
  //       uni.redirectTo({
  //         url: "/authorize/index"
  //       });
  //       clearTimeout(timer);
  //     }, 2000);
  //   }
  // });
}

export function setToken(token) {
  localStorage.setItem("token", token);
}

export function getToken() {
  return localStorage.getItem("token");
}

export function realnameVerifyReq(data) {
  return request({
    url: `${BASE_URL}/hr/api/v1/nameVerifieds`,
    method: "post",
    data
  });
}
export function getPhoneNumber(data) {
  return request({
    header: {
      deviceType: process.env.VUE_APP_DEVICE_TYPE
    },
    url: `${BASE_URL}/user/api/v1/wechat/getPhoneNumberByEncrypt`,
    method: "post",
    data
  });
}
export function checkBindByUnionId(data) {
  return request({
    url: `${BASE_URL}/hr/api/v1/login/checkBindByUnionId`,
    method: "get",
    data
  });
}
